package com.yazi.mxz.person.common;

import java.util.List;

import javax.annotation.Resource;

import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.subject.PrincipalCollection;

import com.yazi.mxz.common.AbstractRealm;
import com.yazi.mxz.common.entity.beans.Member;
import com.yazi.mxz.common.entity.beans.Role;
import com.yazi.mxz.common.entity.enums.RoleType;
import com.yazi.mxz.common.service.RoleService;

/**
 * 
 * 
 * @author mo_yq5@163.com
 * @date 2013-11-22
 * 
 */
public class Realm extends AbstractRealm {
	
	@Resource
	RoleService roleService;

	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection arg0) {
		
		SimpleAuthorizationInfo autho = new SimpleAuthorizationInfo();
		Principal pal = (Principal) arg0.getPrimaryPrincipal();
		if (null != pal.getMember()) {
			List<Role> roles = roleService.listByMemberId(pal.getMember().getMemberId());
			for (Role role : roles) {
				autho.addRole(RoleType.values()[role.getType()].name());
				String[] perms = role.getPerms().split(",");
				for (String perm : perms) {
					autho.addStringPermission(perm);
				}
			}
		}
		return autho;
	}

	@Override
	public AuthenticationInfo getMyAuthenticationInfo(Member member, String password) {
		
		Principal pal = new Principal();
		pal.setMember(member);
		SimpleAuthenticationInfo authe = new SimpleAuthenticationInfo(pal, password,
				Realm.class.getName());
		// SimpleAuthenticationInfo authe = new
		// SimpleAuthenticationInfo(member.getMemberId(), password, getName());
		return authe;
	}

}
